#!/bin/bash

imagedir=testimages/
resultdir=testresults/
kakadudir=../../kakadu-jpeg2k/

echo " images in $imagedir, results placed in $resultdir"

if [[ ! -e $resultdir ]]; then 
   mkdir $resultdir
fi

#show commands as they run.
#set -x 

export DYLD_LIBRARY_PATH=$kakadudir

#build rate string
ratestring=.05
COUNT=2
until [ $COUNT -gt 80 ]; do
    ratestring=$ratestring,`echo "$COUNT * 0.05" | bc`
    let COUNT=COUNT+1	  
done


for fullimgname in $imagedir/*.p[pg]m
do
#remove directory name from fullimgname
  imgname=`basename $fullimgname`     
  currresultdir=$resultdir/$imgname 
  if [[ ! -e $currresultdir ]]; then 
     mkdir $currresultdir
  fi
  echo "processing $imgname"
  statsname=$currresultdir/${imgname}jp2stats.txt
  layersjpegname=$currresultdir/layers${imgname}.jp2
  jpegname=$currresultdir/${imgname}.jp2
  decompname=$currresultdir/jp2recon$imgname

  if [[ ! -e $statsname ]]; then
#create jp2 file
      $kakadudir/kdu_compress -no_weights -i $fullimgname -o $layersjpegname -rate $ratestring  -no_info -quiet  
#decompress file many times. 
      COUNT=1
      until [ $COUNT -gt 80 ]; do
	  currrate=`echo "$COUNT * 0.05" | bc`
#no_weights:=> no perceptual weights used for color images
	  $kakadudir/kdu_compress -i $fullimgname -o $jpegname -rate $currrate -quiet  -no_weights
	  $kakadudir/kdu_expand -i $jpegname -rate $currrate -o $decompname -quiet
          jp2singlemse=`colorimgdist -ycbcr -vo  -mse -compaverage $fullimgname $decompname | tr "\n" \ `
	  $kakadudir/kdu_expand -i $layersjpegname -rate $currrate -o $decompname -quiet
          jp2layermse=`colorimgdist -ycbcr -vo  -mse -compaverage $fullimgname $decompname | tr "\n" \ `
	  echo "$currrate $jp2layermse $jp2singlemse" >> $statsname
	  let COUNT=COUNT+1	  
      done
  fi

#cleanup 
  if [[ -e $jpegname ]]; then 
     rm $jpegname
  fi
  if [[ -e $layersjpegname ]]; then 
     rm $layersjpegname
  fi

  if [[ -e $decompname ]]; then
     rm $decompname
  fi

done
